package com.fcmeditech.AsianSexyGirls;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;


import com.fcmeditech.AsianSexyGirls.File.BitmapManager;
import com.fcmeditech.AsianSexyGirls.PullListView.PullToRefressList;
import com.fcmeditech.AsianSexyGirls.PullListView.PullToRefressList.OnRefreshListener;
import com.fcmeditech.AsianSexyGirls.adwhirl.AdManager;
import com.fcmeditech.AsianSexyGirls.customgallery.ExtendedGallery;




import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;

import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;

import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.ZoomControls;

/**
 * 
 * @author Thuan
 *
 */
public class AsianSexyGirlsActivity extends Activity implements OnClickListener,OnItemClickListener {
	private ViewFlipper viewFliper;
	private int maxValueWidth;
	private int maxValueHeight;
	private int current_page = 1;
	private View layoutLoadmore;
	private int currentScreen 	=-1;
	private int lastScreen=-1;
	private static final int SLIDE_LIST_MAIN_SCREEN	= 0;
	private static final int SLIDE_GALLERY_PICTURE_SCREEN   = 1;
	private static final int SLIDE_GRID_PICTURE_SCREEN   		= 2;
	private static final int SLIDE_VIEW_PICTURE_SCREEN					= 3;
	
	private ProgressDialog progressDialog;
	private static final int SLIDE_PUZZLE_SCREEN		= 2;
	public final static int PROGRESS_DIALOG=0;
	String urlAvatar   		= "http://fcmeditech.com/asiasexygirl/admin/upload/avatar/";	
	String WebserviceDefault    	=	"http://fcmeditech.com/asiasexygirl/getListCategories.php?page=1";
	String WebservicePage   ="http://fcmeditech.com/asiasexygirl/getListCategories.php?page=";
	
	String imgInCategory 		= 	"http://fcmeditech.com/asiasexygirl/admin/upload/images/";
	String webserviceCategory			 = "http://fcmeditech.com/asiasexygirl/getListImageByCate.php?catid=";
	String favoriteFolder="myFavorite";
	int currentIndex =0;
	public SharedPreferences prefs;
	public SharedPreferences.Editor editor;
	ImageButton btn;
	private final static String adwhirlkey = "7e82cceb50e74f288dd465841bc4cfac";
	//private final static String adwhirlkey = "f256a94362eb4019bfdbab8c28b9f986";//sexy show
	private LinearLayout adview;
	
	///////////ListView --Categaries /////////////////////////////
	ArrayList<CategaryObject> sexyLists = new ArrayList<CategaryObject>();
	PullToRefressList list;
    ListAdapter adapter=null;
    
    //////////Gallery --Show Image downloaded////////////////////
    ArrayList<ImageObject> listImg ;//= new ArrayList<ImageObject>();
	Galleryadapter galadapter=null;
	private Gallery gallery;
	
    ////////Grid View--Favorite Image////////////////////
    ArrayList<ImageObject> listFavoriteImg=new ArrayList<ImageObject>();
    GridView myGridView;
    private Gridadapter gadapter;

    /////////For Current image //////////////////////////
    ImageObject imageObject;
    private Bitmap bmp;
    private String nameImage;
    
    private int currentImagePosition=0;
	//private ImageLoaderDefault imageLoader;
	
	boolean isRefreshed = false;
	TextView title2;
	//for 3 buttons= menu
	Button btn1,btn2,btn3;
	//------
	BitmapManager bitmapmanager=new BitmapManager();;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.mainslide);
		viewFliper = (ViewFlipper)findViewById(R.id.vfMainFliper1);		
		/////////////////GET SCREEN SIZE ////////////////////////////
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
		maxValueWidth = display.getWidth();
		maxValueHeight = display.getHeight();

		/////////////////LISTVIEW --CATEGARY/////////////////////////
		list =(PullToRefressList) findViewById(R.id.lvGirls);
		LayoutInflater inflater = getLayoutInflater();
		layoutLoadmore = (View) inflater.inflate(R.layout.loadmore, list, false);
		//Type face face=Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf"); 
        list.addFooterView(layoutLoadmore);
        
		CreateListView();// create list view;
		
		new ReadJSONFeedTask().execute(WebserviceDefault);
		//	btnLoad.setTypeface(face);
		list.setOnRefreshListener(new OnRefreshListener() {
	          
	            public void onRefresh() {
	                // Do work to refresh the list here.
	                RefreshListview();
	            }
	        });
	
		///////////////GALLERY --SHOW IMAGES /////////////////////////
		
		gallery =(Gallery) findViewById(R.id.galleryDisplay);
		//CreateGallery();
		
		title2 = (TextView) findViewById(R.id.tvNameOfCategory);
		
		//imgView = (ImageView) findViewById(R.id.imageDisplay);
		
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View view,
					int position, long arg3) {
					
				/*imageObject  = listImg.get(currentIndex);
				bmp=null;
				bmp = imageObject.getmImage();
				nameImage = imageObject.getmNameImg();
				if(bmp!=null)*/
				//currentImagePosition=position;
				showMemory("Photo "+position);
			
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		gallery.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				VisibleButtons();
			}
			
		});
		CreateGallery();
		
		////Activate Buttons ------------------------------------------
		Button btnLoad = (Button)layoutLoadmore.findViewById(R.id.btnLoadmore);
        btnLoad.setOnClickListener(this);
        ImageButton btnHome = (ImageButton) findViewById(R.id.ibHome) ;
		btnHome.setOnClickListener(this);
		ImageButton btnfavous = (ImageButton) findViewById(R.id.ibFavorite) ;
		btnfavous.setOnClickListener(this);
		/////////////////GRID --FAVORITE IMAGES////////////////////////
		myGridView =(GridView) findViewById(R.id.gridfavous);
		
		//CreateGrid(); //2,5s for 3 images
		
		ImageButton temp=(ImageButton) findViewById(R.id.ibHomeGrid);
		temp.setOnClickListener(this);
		temp=(ImageButton) findViewById(R.id.ibEdit);
		temp.setOnClickListener(this);
		//------for menu=3button-------------------------
		btn1=(Button)findViewById(R.id.btnGridShare);
		btn1.setOnClickListener(this);
		btn2=(Button)findViewById(R.id.btnGridDelete);
		btn2.setOnClickListener(this);
		btn3=(Button)findViewById(R.id.btnGridCancel);
		btn3.setOnClickListener(this);
		btn1.setVisibility(View.INVISIBLE);
		btn2.setVisibility(View.INVISIBLE);
		btn3.setVisibility(View.INVISIBLE);
		//////////////////////////////////////////////////////////////????
		showMainMenu();
		//check Heap Size
		Runtime rt = Runtime.getRuntime();
		long maxMemory = rt.maxMemory();
		Log.d(null, "maxMemory: " + maxMemory);
		
		showMemory("JustStartActivity");
    }
    
	////////////////////////////////FOR ALL BUTTONS- EVENT//////////////////////////////////////
	public void onClick(View v) {
		//TODO all click event
	int viewID = v.getId();
	switch (viewID) {
	case R.id.btnLoadmore:
		new loadMoreListview().execute();
		break;
	case R.id.ibNext:
	
		if (currentIndex == (listImg.size()-1)) currentIndex = -1;
		currentIndex++;
		gallery.setSelection(currentIndex);
		
		break;
	case R.id.ibPreview:
		
		if (currentIndex == 0) currentIndex =listImg.size();
		currentIndex--;
		gallery.setSelection(currentIndex);
		
		break;	
	case R.id.ibHome:
		//clear arrylist
		listImg.clear();
		//listImg=null;
		//gadapter=null;
		//gallery=null;
		showMainMenu();
		break;
	case R.id.ibFavorite:
		CreateGrid();
		resetParams();
		setToFavoris(currentIndex);
		//setToFavoris(currentImagePosition);
		//setToFavoris(imageObject);
		break;
	case R.id.ibHomeGrid : slide(SLIDE_LIST_MAIN_SCREEN,true);
		break;
	case R.id.ibEdit : 
		changeVisibleMenu();
		changeVisibleCheckbox(); 
		//**************For Context Menu*****************************//
		//this.registerForContextMenu(v);
		//v.setLongClickable(false);
		//this.openContextMenu(v);
		break;
	case R.id.btnGridDelete: 
		int cnt=0;
		for(ImageObject img:listFavoriteImg){
			if(img.getCheckStatus())cnt++;
		}
		Toast.makeText(getBaseContext(), "You have just chosen " +cnt+ " photos", Toast.LENGTH_SHORT).show();
		
		deleteSDCardImage();
		break;
	case R.id.btnGridCancel: 
		resetParams();
	    for(ImageObject obj:listFavoriteImg) obj.setCheckStatus(false);
	    gadapter.notifyDataSetChanged();
	    break;
	}
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (currentScreen == SLIDE_GALLERY_PICTURE_SCREEN) {	
				showMainMenu();
				return true;
			}else if (currentScreen ==SLIDE_GRID_PICTURE_SCREEN) {
				slide(SLIDE_GALLERY_PICTURE_SCREEN, true);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	////********************************PAGE 1: LISTVIEW *****************************************************
	public void CreateListView(){
		
		adapter=new ListAdapter(this,sexyLists);
		list.setAdapter(adapter);
		list.setOnItemClickListener(this);
		
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position , long arg3) {
		//TODO when Click to item of ListView
		
		
		if (currentScreen == SLIDE_LIST_MAIN_SCREEN){	
			currentIndex=0; //refresh current Index of image, if not, when choose another category -->choose wrong when 
			// click button Next, Previous
			showPicture(sexyLists.get(position-1)); //Tap is position 0.
			//Toast.makeText(getBaseContext(), "Album: "+ position, Toast.LENGTH_SHORT).show();
			showMemory("Scroll Listview "+position);
		}	
		
	}
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case PROGRESS_DIALOG:
			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Loading ...");
			progressDialog.setCancelable(true);
			return progressDialog;
		}
		return super.onCreateDialog(id); 
	}

	public void updateListview(){
		
		adapter = new ListAdapter(this,sexyLists );
		list.setAdapter(adapter);
		list.setOnItemClickListener(this);
		layoutLoadmore.setVisibility(View.VISIBLE);
		dismissDialog(PROGRESS_DIALOG);
	}
	
	private void showMainMenu() {		
		slide(SLIDE_LIST_MAIN_SCREEN,true);			

	}
	
	private void showPicture(CategaryObject object) {		
			slide(SLIDE_GALLERY_PICTURE_SCREEN,true);
			
			//TextView view = (TextView) findViewById(R.id.tvNameOfCategory);
			title2.setText(object.getCateName());
			//Activate Buttons
			ImageButton ibutton = (ImageButton) findViewById(R.id.ibNext) ;
			ibutton.setOnClickListener(this);
			ImageButton ibPre = (ImageButton) findViewById(R.id.ibPreview) ;
			ibPre.setOnClickListener(this);	
			CreateGallery();
			//listImg=new ArrayList<ImageObject>();
			new GetDetailImage().execute(webserviceCategory+object.getCateID());
			
			
		}
	
	private void RefreshListview(){
		slide(SLIDE_LIST_MAIN_SCREEN,true);
		sexyLists.clear();
		list.addFooterView(layoutLoadmore);
		new ReadJSONFeedTask().execute(WebserviceDefault);
	}

	////********************************PAGE 2: GALLERY  *****************************************************
	//------------------For Gallery---------------------------------------
	private void CreateGallery(){
		listImg= new ArrayList<ImageObject>();
		galadapter = new Galleryadapter(AsianSexyGirlsActivity.this, listImg,gallery);//
		gallery.setAdapter(galadapter);
		//gallery.setScrollingEnabled(false); 
		Log.d(null, "Time of drawing Gallery "+gallery.getDrawingTime());
		
	}
	private void setToFavoris(int position) { //imgToGrid had image property
		slide(SLIDE_GRID_PICTURE_SCREEN ,true);
		ImageObject imgToGrid=listImg.get(position);
		listFavoriteImg.add(0,imgToGrid);
		
		gadapter.notifyDataSetChanged();
		//save to SDcard:
		SaveSDCard(imgToGrid.getmImage(),imgToGrid.getmNameImg(),favoriteFolder);
		
		/*imgToGrid.getmImage().recycle();	
		imgToGrid.setmImage(null);
		imgToGrid=null;*/
		
	}
	
	private void setToFavoris(ImageObject imgToGrid) { //imgToGrid had image property
		slide(SLIDE_GRID_PICTURE_SCREEN ,true);
		listFavoriteImg.add(0,imgToGrid);
		
		gadapter.notifyDataSetChanged();
		//save to SDcard:
		SaveSDCard(imgToGrid.getmImage(),imgToGrid.getmNameImg(),favoriteFolder);
	}
	
	private void resetParams(){
		//to enter page 3, reset all params about visible or not of Check and Menu, CheckBox -->not checked.
		currentImagePosition=0;
		image_checkbox_status=false;
		grid_menu_status =false;
		ImageObject.status=false;
		gadapter.notifyDataSetChanged();
		btn1.setVisibility(View.INVISIBLE);
		btn2.setVisibility(View.INVISIBLE);
		btn3.setVisibility(View.INVISIBLE);	
		//for(ImageObject obj:listFavoriteImg)obj.setCheckStatus(false);
		
	}
	//------------------For invisible buttons----------------------------------
	private boolean status_Buttons=false;

	private void VisibleButtons(){
		ImageButton btnHome=(ImageButton)findViewById(R.id.ibHome);
		ImageButton btnFavorite=(ImageButton)findViewById(R.id.ibFavorite);
		if(status_Buttons){
			btnHome.setVisibility(View.VISIBLE);
			btnFavorite.setVisibility(View.VISIBLE);
			status_Buttons=false;
			
		}else {
			btnHome.setVisibility(View.INVISIBLE);
			//btnHome.setBackgroundColor(Color.TRANSPARENT);
			btnFavorite.setVisibility(View.INVISIBLE);
			//btnFavorite.setBackgroundColor(Color.TRANSPARENT);
			status_Buttons=true;
		}
	}
	//-------------------For menu -------------------------------------------
	private static final int FAVORITE		= 0;
	private static final int SET_AS_WALL_PAPER		= 1;
	private static final int GET_MORE						= 2;
	private static final int TELL_FRIENDS							= 3;
	private static final int RATE_US										= 4;
	private static final int SAVE_SDCARD 											= 5;
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuItem mn1 =menu.add(0,FAVORITE , 0,"Favorite");
		{
			mn1.setAlphabeticShortcut('f');
		
		}
		MenuItem mn2 =menu.add(0,SET_AS_WALL_PAPER,0, "Set As Wall Paper");
		{
			mn2.setAlphabeticShortcut('s');
		}
		MenuItem mn3 =menu.add(0,GET_MORE, 0, "Get More");
		{
			mn3.setAlphabeticShortcut('g');
			
		}
		MenuItem mn4 =menu.add(0, TELL_FRIENDS, 0, "Tell Friends");
		{
			mn4.setAlphabeticShortcut('t');				
		}
		MenuItem mn5 = menu.add(0, RATE_US, 0, "Rate us");
		{
			mn5.setAlphabeticShortcut('r');				
		}
		MenuItem mn6 = menu.add(0,SAVE_SDCARD,0,"Save SD Card");
		{
			mn6.setAlphabeticShortcut('c');
		}
		return super.onCreateOptionsMenu(menu);		
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		
		// TODO Menu
		switch(currentScreen)
		{
		case SLIDE_LIST_MAIN_SCREEN: menu.setGroupVisible(0, false);
			break;
		case SLIDE_GALLERY_PICTURE_SCREEN: menu.setGroupVisible(0, true);
			break;
		case SLIDE_GRID_PICTURE_SCREEN : menu.setGroupVisible(0, false);
		}
		
		return super.onPrepareOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
			int id = item.getItemId();		
			switch (id) {
			case FAVORITE:
				CreateGrid();
				Favorite();
				return true;		
			case SET_AS_WALL_PAPER:
				SetWallPaper();
				return true;
			case GET_MORE:
				GetMore();
				return true;
			case TELL_FRIENDS:
				TellFriends();
				return true;
			case RATE_US:
				RateUs();
				return true;
			case SAVE_SDCARD:
				SaveSDCard();
			}
			return false;
		}
    ///--------------------------for detail items ---------------------------------
	private void SaveSDCard() { 
		if(bmp==null) return ; ///added
		  String newFolder = "/myFiles2";
	      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
	      File myNewFolder = new File(extStorageDirectory + newFolder);
	      myNewFolder.mkdirs();
		File file = new File(myNewFolder, nameImage);
		FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
				bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
	   
			} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
	   
			} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
	    
			}
	   }
	private void SaveSDCard(Bitmap img,String imgName,String foldername) { 
		if(img==null) return ; ///added
		//else:
		  String newFolder = "/"+foldername;//"/myFiles2";
	      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
	      File myNewFolder = new File(extStorageDirectory + newFolder);
	      myNewFolder.mkdirs();
	      
	      File file = new File(myNewFolder, imgName);
	      FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
				img.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				fos.flush();
				fos.close();
	   
			} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
	   
			} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
	    
			}
	   }
	private void Favorite() {
		slide(SLIDE_GRID_PICTURE_SCREEN,true);	
		
		
	}
	private void TellFriends() {
		 Intent intent = new Intent(Intent.ACTION_SEND);
		    intent.setType("text/plain");
		    intent.putExtra(Intent.EXTRA_TEXT, "The status update text");
		    startActivity(Intent.createChooser(intent, "Dialog title text"));
		
		
	}
	private void RateUs(){		
		Intent rateuintent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store"));
		startActivity(rateuintent);
		
		
	}
	//TODO Link Url
	private void GetMore() {
		Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
		startActivity(browserIntent);
	}
	//TODO Set Wallpaper
	public void SetWallPaper(){
     
		try {
				Bitmap bm = Bitmap.createScaledBitmap(bmp, maxValueWidth, maxValueHeight, true);
				
			     getApplicationContext().setWallpaper(bm);
			     Toast.makeText(getBaseContext(), "Set Wallpaper Success Fully", Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			     // TODO Auto-generated catch block
			     e.printStackTrace();
			    }
		}

	////********************************PAGE 3: GRID VIEW ****************************************************
	//------------------Show image ,check box----------------------------------------
	//when using the function ???
	private void CreateGrid(){
		long loadTime=System.currentTimeMillis();
		
		listFavoriteImg=getSDCardImage(favoriteFolder); //test time
		
		loadTime=System.currentTimeMillis()-loadTime;
		Log.d(null,"Time to get images from SD Card: "+loadTime +"/Image numbers: "+listFavoriteImg.size());
		
		gadapter = new Gridadapter(this, listFavoriteImg);
		myGridView.setAdapter(gadapter);
	}
	
	private ArrayList<ImageObject> getSDCardImage(String foldername){
		ArrayList<ImageObject> xList=new ArrayList<ImageObject>();
		//Folder name--> folder path.
		File cacheDir;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),foldername);
            try{
            	File[] files=cacheDir.listFiles();
                for(File f:files){
                	//file --> InputStream
                	InputStream is=new FileInputStream(f);
                	//decode InputStream -->bitmap
                	Bitmap temp=BitmapFactory.decodeStream(is);
                	if(temp!=null){
                		ImageObject ximg=new ImageObject();
                		ximg.setmImage(temp);
                		ximg.setmNameImg(f.getName());
                		Log.d(null,"File name "+f.getName());
                		//add to List
                		xList.add(ximg);
                	}
                }
            }
            catch(Exception e){
            	//Log.e("Error: ", e.getMessage());
            	e.printStackTrace();
            }
		}
		return xList;
	}
	private void deleteSDCardImage(){
		for(ImageObject obj: listFavoriteImg){
			if(obj.getCheckStatus()){ //true -->chosen; false -->no choose
			String image_name=obj.getmNameImg();
			//name-->file path
			String imagePath = Environment.getExternalStorageDirectory().toString()+"/"+favoriteFolder+"/"+image_name;
			Log.d(null,"imagePath: "+imagePath);
			//delete
			File f=new File(imagePath);
			f.delete();
			
			}
		}
		try
		{
		 /*for(ImageObject obj: listFavoriteImg){
			if(obj.getCheckStatus()){ //true -->chosen; false -->no choose
				listFavoriteImg.remove(obj);
				gadapter.notifyDataSetChanged();
			}
		}*/ int N=listFavoriteImg.size()-1;
			for(int i=N;i>=0;i--){
				if(listFavoriteImg.get(i).getCheckStatus()) listFavoriteImg.remove(i);
			}
		} catch(Exception e){
			//e.getStackTrace();
			e.printStackTrace();
			Log.d(null,"Error to delete ArrayList");
		}
		
		resetParams();
		
		gadapter.notifyDataSetChanged();
		
		
	}
	
	private boolean image_checkbox_status=false;
	
	private void changeVisibleCheckbox(){
		
		if(image_checkbox_status){
			
			image_checkbox_status=false;
		}
		else {
			image_checkbox_status=true;
		}
		ImageObject.status=image_checkbox_status;
		//update grid view
		gadapter.notifyDataSetChanged();
	}
	
	private boolean grid_menu_status =false;
	private void changeVisibleMenu(){
		
		//when click button EDIT --> then status of 3 buttons changes --->Visible
		if(grid_menu_status){
			grid_menu_status=false;
			btn1.setVisibility(View.INVISIBLE);
			btn2.setVisibility(View.INVISIBLE);
			btn3.setVisibility(View.INVISIBLE);
			
		}
		else {
			grid_menu_status=true;
			btn1.setVisibility(View.VISIBLE);
			btn2.setVisibility(View.VISIBLE);
			btn3.setVisibility(View.VISIBLE);
			
		}
		
	}
	//------------------Context Menu  not used----------------------------------------------
	private static final int SELECT_SHARE  	= 0;
	private static final int SELECT_DELETE	=	1;
	private static final int SELECT_CANCEL	=		2;
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		//return super.onContextItemSelected(item);
		int id = item.getItemId();		
		switch (id) {
		
		}
		return false;
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu,v,menuInfo);
		//if(v.getId()==R.id.ibEdit){
			CreateSelectionMenu(menu);
		//}
	} 
	private void CreateSelectionMenu(Menu menu){
		menu.setQwertyMode(true);
		MenuItem mn1 =menu.add(0,SELECT_SHARE , 0,"Share");
		{
			mn1.setAlphabeticShortcut('s');
		
		}
		MenuItem mn2 =menu.add(0,SELECT_DELETE,0, "Delete");
		{
			mn2.setAlphabeticShortcut('d');
		}
		MenuItem mn3 =menu.add(0,SELECT_CANCEL, 0, "Cancel");
		{
			mn3.setAlphabeticShortcut('n');
			
		}
	}
				
    /////********************Read JSON, download Image, save to Memory ****************************************
			
		private class GetDetailImage extends AsyncTask<String, Void, String> {
			
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				//showDialog(PROGRESS_DIALOG);
			}      
	        protected String doInBackground(String... urls) {
	            return readJSONFeed(urls[0]);
	        }
	        
	        protected void onPostExecute(String result) {
	        	try {
	        		
	        		ParserJSONImage2(result);
	    			//dismissDialog(PROGRESS_DIALOG);
	    			
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    		}        
	        }	

			  
	    }
		
		private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
	        
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
					//
					if(!isRefreshed)showDialog(PROGRESS_DIALOG);
					layoutLoadmore.setVisibility(View.INVISIBLE);
			}        
			
			protected String doInBackground(String... urls) {
	            String result=readJSONFeed(urls[0]); //from internet
	            return result;

	        }
	        
	        protected void onPostExecute(String result) {

	        	ParserJSONCategory2(result); //Parser + update ListView
	        	
	        	if(isRefreshed) dismissDialog(PROGRESS_DIALOG);
	    		isRefreshed=true;
	        	
	        	layoutLoadmore.setVisibility(View.VISIBLE);
				dismissDialog(PROGRESS_DIALOG);
	    		list.onRefreshComplete(); 
	        }

			
	    }
		private class loadMoreListview extends AsyncTask<Void, Void, Void> {
			 
		    @Override
		    protected void onPreExecute() {
		        // Showing progress dialog before sending http request
		    	super.onPreExecute();
				showDialog(PROGRESS_DIALOG);
		    }
		
		    protected Void doInBackground(Void... unused) {
		        runOnUiThread(new Runnable() {
		            public void run() {
		                // increment current page
		                current_page += 1;                   
		                String url = WebservicePage+current_page;
		                try {
		                	String result = readJSONFeed(url);
		                	ParserJSONCategory2(result);

		        			dismissDialog(PROGRESS_DIALOG);
		        			// get list view current position - used to maintain scroll position
		                    int currentPosition = list.getFirstVisiblePosition(); 
		                	
		                    // Setting new scroll position
		                    list.setSelectionFromTop(currentPosition + 1, 0);       		   	
		                }
		             catch (Exception e) {
		    			e.printStackTrace();
		             	} 
		            }
		        });
		        return (null);
		     
		    }
		
		    protected void onPostExecute(Void unused) {
		        // closing progress dialog
		        dismissDialog(PROGRESS_DIALOG);
		    }
		}

		//Parser + update ListView
		private void ParserJSONCategory2(String jsText){  

			//sexyLists=new ArrayList<CategaryObject>();
			try{
				final JSONArray entries = new JSONArray(jsText);
			    
				JSONObject post=null;
				int i;
				for (i=0;i<entries.length();i++)
				{       		
					post = entries.getJSONObject(i);
					CategaryObject sexy = new CategaryObject(
							post.getString("id"),
							urlAvatar + post.getString("avatar"), 
							post.getString("cat_name"),
							post.getString("pubdate"));
					sexyLists.add(sexy);     	
				}
				//update ListView
				adapter.notifyDataSetChanged();
				Log.d(null, "Number of Album: "+sexyLists.size());
				
				if(sexyLists.size()==0)Toast.makeText(getBaseContext(), "Error JSON !!!", Toast.LENGTH_LONG).show();
			}catch (Exception e) {
    			e.printStackTrace();
    			
    		}        
			//layoutLoadmore.setVisibility(View.VISIBLE);
			//dismissDialog(PROGRESS_DIALOG);
			
		}
		
		private ArrayList<CategaryObject> ParserJSONCategory(String jsText){

			ArrayList<CategaryObject> cateList=new ArrayList<CategaryObject>();
			try{
				final JSONArray entries = new JSONArray(jsText);
			    
				JSONObject post=null;
				int i;
				for (i=0;i<entries.length();i++)
				{       		
					post = entries.getJSONObject(i);
					CategaryObject sexy = new CategaryObject(
							post.getString("id"),
							urlAvatar + post.getString("avatar"), 
							post.getString("cat_name"),
							post.getString("pubdate"));
					cateList.add(sexy);       			
				}
			}catch (Exception e) {
    			e.printStackTrace();
    		}        
			return cateList;
		}
		private void ParserJSONImage2(String jsText){
			
			try{
				//set time to estimate!
				
				final JSONArray entries = new JSONArray(jsText);
//				Debugs.DebugsINFO("JSON>>Detail image", "Number of surveys in feed: " + entries.length());
				JSONObject post=null;
				int i;
				for (i=0;i<entries.length();i++)
				{       
					//long jsontime=System.currentTimeMillis();
					post = entries.getJSONObject(i);
					///Check  if  image = null =>> set default for image       		 
					ImageObject img = new ImageObject(imgInCategory +post.getString("link_image"),post.getString("link_image"));        			       		        			
					listImg.add(img);
					//Toast.makeText(getBaseContext(), " Finish Parser  " + i, Toast.LENGTH_SHORT).show();
					//galadapter.notifyDataSetChanged();	
					//jsontime=System.currentTimeMillis()-jsontime;
					//Toast.makeText(getBaseContext(), " Finish Parser: "+i+ "-jsonTime:"+jsontime, Toast.LENGTH_SHORT).show();
					
					
				}
				//jsontime=System.currentTimeMillis()-jsontime;
				//Toast.makeText(getBaseContext(), " Finish Parser...jsonTime:"+jsontime, Toast.LENGTH_SHORT).show();
				Toast.makeText(getBaseContext(), "Number of Pictures = "+ listImg.size(), 5000).show();
				galadapter.notifyDataSetChanged();
				Log.d(null,"Number of images: "+listImg.size());
				
			}
			catch (Exception e) {
	    			e.printStackTrace();
	    	}     
			
		}
		private ArrayList<ImageObject> ParserJSONImage(String jsText){
			ArrayList<ImageObject> list=new ArrayList<ImageObject>();
			try{
				final JSONArray entries = new JSONArray(jsText);
//				Debugs.DebugsINFO("JSON>>Detail image", "Number of surveys in feed: " + entries.length());
				JSONObject post=null;
				int i;
				for (i=0;i<entries.length();i++)
				{       		
					post = entries.getJSONObject(i);
					///Check  if  image = null =>> set default for image       		 
					ImageObject img = new ImageObject(imgInCategory +post.getString("link_image"),post.getString("link_image"));        			       		        			
					list.add(img);  
    			
				}
			}
			catch (Exception e) {
	    			e.printStackTrace();
	    	}     
			return list;
			
		}
		private String readJSONFeed(String URL) {
			StringBuilder stringBuilder = new StringBuilder();
			HttpClient client = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(URL);
			try {
				HttpResponse response = client.execute(httpGet);
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if (statusCode == 200) {
					HttpEntity entity = response.getEntity();
					InputStream content = entity.getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(content));
					String line;
					while ((line = reader.readLine()) != null) {
						stringBuilder.append(line);
					}
				} else {
	//				Debugs.DebugsERROR("JSON", "Failed to download file");
					Log.e("JSON", "Failed to download file");	
					Toast.makeText(getBaseContext(), "Error connect internet", Toast.LENGTH_SHORT).show();
				}
			} catch (ClientProtocolException e) {
	//			Debugs.DebugsERROR("ClientProtocolException", "ClientProtocolException");
				e.printStackTrace();
			} catch (IOException e) {
	//			Debugs.DebugsERROR("IOException", "IOException");
				e.printStackTrace();
			}
			return stringBuilder.toString();
		}
/////////////////////////////OLD STANDARD FUNCTION///////////////////////////////////////////////
		private void slide(int newSlide, boolean n2c) {
			if (n2c && newSlide == currentScreen) return; 
			viewFliper.setInAnimation(inFromRightAnimation());
			viewFliper.setOutAnimation(outToLeftAnimation());
			viewFliper.setDisplayedChild(newSlide);
			lastScreen = currentScreen;
			currentScreen = newSlide;
		}
		
	   
	    private Animation inFromRightAnimation() {
			Animation inFromRight = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
					Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
					);
			inFromRight.setDuration(000);//500
			inFromRight.setInterpolator(new AccelerateInterpolator());
			return inFromRight;
		}

		
		private Animation outToLeftAnimation() {
			Animation outtoLeft = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
					Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
					);
			outtoLeft.setDuration(000);//500
			outtoLeft.setInterpolator(new AccelerateInterpolator());
			return outtoLeft;
		}
		///NOT USED/////
				public void updateListview2(){
					ArrayList<CategaryObject> data=new ArrayList<CategaryObject>();
					adapter = new ListAdapter(this,data );
					list.setAdapter(adapter);
					list.setOnItemClickListener(this);
					for(int i=0;i<sexyLists.size();i++){
						data.add(sexyLists.get(i));
						adapter.notifyDataSetChanged();
					}
					layoutLoadmore.setVisibility(View.VISIBLE);
					dismissDialog(PROGRESS_DIALOG);
					
				}
	////on Destroy, On Pause
				
    private static void showMemory(String label){
    	Runtime rt=Runtime.getRuntime();
    	long free=rt.freeMemory();
    	long total=rt.totalMemory();
    	long used=total-free;
    	Log.d(null,label+ "-"+"Free memory: "+free+ " Total Memory: "+total+" Used: "+used);
    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//list.removeAllViews();
		adapter=null;
		list=null;
		System.gc();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.gc();
	}
    
}